package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.duowei.diandan.R;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.QrCodePay;
import com.duowei.diandan.constant.QrCodeType;
import com.duowei.diandan.databinding.QrCodePayFragmentBinding;
import com.duowei.diandan.db.entry.PaySet;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.util.DateTimes;
import com.duowei.diandan.util.NetUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;

public class QrCodePayFragment extends BaseFragment {
    public static final String TAG = "QrCodePayFragment";

    private QrCodePayFragmentBinding mBinding;
    private QrCodeType mType;

    private String mPayUrl;
    private String mPayQueryUrl;
    private String mWeiOrZfbId;
    private float mPayMoney;
    /** 付款码扫描数据 */
    private String mAuthCode;

    private Handler mHandler = new Handler();

    private QrCodePay mQrCodePay = new QrCodePay();

    private boolean mPaySuccess = false;

    private TextView.OnEditorActionListener mAuthCodeOnEditorActionListener = (v, actionId, event) -> {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            mAuthCode = v.getText().toString();
            v.setText(null);

            if (mType == QrCodeType.WECHATPAY && !mAuthCode.startsWith("1")) {
                EventBus.getDefault().post(new ToastEvent("请使用微信付款码进行支付", false));
                return true;
            } else if (mType == QrCodeType.ALIPAY && !mAuthCode.startsWith("2")) {
                EventBus.getDefault().post(new ToastEvent("请使用支付宝付款码进行支付", false));
                return true;
            }

            new Thread(new ProcessDataRunnable()).start();

            return true;
        } else {
            return false;
        }
    };

    private OnStatusListener mOnStatusListener;

    public void setOnStatusListener(OnStatusListener onStatusListener) {
        mOnStatusListener = onStatusListener;
    }

    public interface OnStatusListener {

        void onCloseClick();

        void onPaySuccess();

    }

    public static QrCodePayFragment newInstance(QrCodeType type, float payMoney) {

        Bundle args = new Bundle();
        args.putString("QrCodeType", type.name());
        args.putFloat("PayMoney", payMoney);

        QrCodePayFragment fragment = new QrCodePayFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mType = QrCodeType.valueOf(args.getString("QrCodeType"));
            mPayMoney = args.getFloat("PayMoney");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_qr_code_pay, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mQrCodePay.setPrice(mPayMoney);
        OrderList.getInstance().setQrCodePay(null);

        mBinding.closeLayout.setOnClickListener(v -> {
            if (mOnStatusListener != null) {
                mOnStatusListener.onCloseClick();
            }
        });

        mBinding.payMoneyView.setPrice(mPayMoney);

        if (mType == QrCodeType.WECHATPAY) {
            mQrCodePay.setTitle("微信支付");
            mBinding.navView.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_weixin_pay_nav));

        } else if (mType == QrCodeType.ALIPAY) {
            mQrCodePay.setTitle("支付宝支付");
            mBinding.navView.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_alipay_nav));
        }

        mBinding.noImeEditText.setOnEditorActionListener(mAuthCodeOnEditorActionListener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPayQueryThread != null) {
            mPayQueryThread.interrupt();
        }
    }

    private int getNumber() {
        Random random = new Random();
        return random.nextInt(100000);
    }

    private class ProcessDataRunnable implements Runnable {

        @Override
        public void run() {
            PaySet ps = getDb().paySetDao().findOne();
            if (ps == null) {
                showMessage("没有支付信息设置");

            } else {
                // Url中文处理
                String by2 = "";
                if (!TextUtils.isEmpty(ps.getBy2())) {
                    try {
                        by2 = URLEncoder.encode(ps.getBy2(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, "handlePay: ", e);
                        by2 = ps.getBy2();
                    }
                }

                //生成10W以内随机数
                mWeiOrZfbId = DateTimes.getTime() + getNumber();

                // 根据支付设置处理url
                // 付款码支付
                if (!TextUtils.isEmpty(mAuthCode) && mAuthCode.length() != 18) {
                    showMessage("付款码格式错误");
                    return;
                }

                if (mAuthCode.startsWith("1")) {
                    // 微信
                    mQrCodePay.setTitle("微信支付");

                    String by7 = ps.getBy7();
                    if (TextUtils.isEmpty(by7)) {
                        showMessage("未设置微信支付调用方式");
                        return;
                    }

                    if (by7.equals("原生态接口")) {
                        mPayUrl = "http://" + ps.getFwqdz() + "/yst/pay/micropay_call.php?" +
                                "weid=" + ps.getBy3() +
                                "&orderid=" + mWeiOrZfbId +
                                "&spmc=" + ps.getBy1() + by2 +
                                "&money=" + mPayMoney +
                                "&auth_code=" + mAuthCode;

                        mPayQueryUrl = "http://" + ps.getFwqdz() + "/yst/pay/order_query.php?" +
                                "orderid=" + mWeiOrZfbId +
                                "&weid=" + ps.getBy3();

                    } else if (by7.equals("服务商接口")) {
                        mPayUrl = "http://" + ps.getFwqdz() + "/bs/wxzf/micropay_call.php?" +
                                "weid=" + ps.getBy3() +
                                "&orderid=" + mWeiOrZfbId +
                                "&spmc=" + ps.getBy1() + by2 +
                                "&money=" + mPayMoney +
                                "&auth_code=" + mAuthCode;

                        mPayQueryUrl = "http://" + ps.getFwqdz() + "/bs/wxzf/order_query.php?" +
                                "orderid=" + mWeiOrZfbId +
                                "&weid=" + ps.getBy3();
                    }

                } else if (mAuthCode.startsWith("2")) {
                    // 支付宝
                    mQrCodePay.setTitle("支付宝支付");

                    mPayUrl = "http://" + ps.getFwqdz() + "/aipay/f2fpay/barpay.php?" +
                            "appid=" + ps.getPid() +
                            "&out_trade_no=" + mWeiOrZfbId +
                            "&subject=" + ps.getBy1() + by2 +
                            "&total_amount=" + mPayMoney +
                            "&store_id=" + ps.getBy1() +
                            "&auth_code=" + mAuthCode;

                    mPayQueryUrl = "http://" + ps.getFwqdz() + "/aipay/f2fpay/query.php?" +
                            "out_trade_no=" + mWeiOrZfbId +
                            "&appid=" + ps.getPid();

                } else {
                    showMessage("请使用微信付款码或支付宝付款码,进行付款");
                    return;
                }

                try {
                    String result = NetUtils.get(mPayUrl).body().string();
                    if (result.contains("支付成功") || result.contains("SUCCESS")) {
                        paySuccess(result);

                    } else {
                        QrCodePayFragment.this.mPayQueryThread = new Thread(QrCodePayFragment.this.mPayQueryRunnable);
                        QrCodePayFragment.this.mPayQueryThread.start();
                    }

                } catch (IOException e) {
                    Log.e(TAG, "ProcessDataRunnable", e);
                }
            }
        }
    }

    private void showMessage(String message) {
        EventBus.getDefault().post(new ToastEvent(message, false));
    }

    private Thread mPayQueryThread;

    private Runnable mPayQueryRunnable = () -> {

        while (true) {
            if (Thread.currentThread().isInterrupted()
                    || InitManager.getInstance().getCountdownSecond() <= 0) {
                break;
            }

            try {
                String result = NetUtils.get(mPayQueryUrl).body().string();

                if (result.contains("支付成功") || result.contains("SUCCESS")) {
                    Thread.currentThread().interrupt();

                    paySuccess(result);
                } else {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }

            } catch (IOException e) {
                Log.e(TAG, "PayQueryRunnable", e);

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    };

    @WorkerThread
    private synchronized void paySuccess(String result) {
        if (mPaySuccess) {
            return;
        }
        mPaySuccess = true;

        String zfbid = null;
        if (mType == QrCodeType.ALIPAY
                || (mAuthCode != null && mAuthCode.startsWith("2"))) {
            zfbid = result.substring(result.indexOf("*") + 1, result.length());
        }

        // --
        Wmlsbjb wmlsbjb = getDb().wmlsbjbDao().findOne();
        wmlsbjb.setBy13(mWeiOrZfbId);
        wmlsbjb.setBy16(zfbid);
        getDb().wmlsbjbDao().update(wmlsbjb);

        mHandler.post(() -> {
            OrderList.getInstance().setQrCodePay(mQrCodePay);

            if (mOnStatusListener != null) {
                mOnStatusListener.onPaySuccess();
            }
        });
    }
}
